﻿using DoctorClient.Common;
using QMS.Core.Loading;
using QMS.Core.Common;
using QMS.Core.Model;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using static QMS.Core.Common.RedisHelper;

namespace DoctorClient
{
    public partial class MainForm : Form
    {
        static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public MainForm()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private PatientInfo currentPatient = null;//当前就诊病人
        private List<PatientInfo> patientList = null;//当前就诊病人列表

        RedisHelper redisHelper = new RedisHelper();

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                #region 初始化控件

                this.lvPatientList.View = View.Details;
                this.lvPatientList.FullRowSelect = true;
                this.lvPatientList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

                //添加列标题
                this.lvPatientList.Columns.Add("显示号", 60, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("排队号", 60, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("姓名", 80, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("性别", 50, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("年龄", 50, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("备注", 120, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("状态", 80, HorizontalAlignment.Center);
                this.lvPatientList.Columns.Add("门诊号", -2, HorizontalAlignment.Center);//-2 自动调整列宽

                #endregion

                // 初始化数据
                LoadData();
            }
            catch (Exception ex)
            {
                log.Error("程序初始化异常！", ex);
                MessageBox.Show("程序初始化异常！原因：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
#if DEBUG
                /*
                License.Core.Common.LicenseHelper.ProductKey = "DoctorClient";//产品标识码
                License.Core.Common.LicenseHelper.NeedMachineNo = true;//是否需要机器码
                License.Core.Common.LicenseHelper.LicenseType = License.Core.Common.LicenseHelper.LicenseTypeEnum.RSA;//License加密类型
                License.Core.Common.LicenseHelper.ForceExit = true;//是否需要强制退出
                License.Core.Common.LicenseHelper.LoadRegister();
                */
#else
                License.Core.Common.LicenseHelper.ProductKey = "DoctorClient";//产品标识码
                License.Core.Common.LicenseHelper.NeedMachineNo = true;//是否需要机器码
                License.Core.Common.LicenseHelper.LicenseType = License.Core.Common.LicenseHelper.LicenseTypeEnum.RSA;//License加密类型
                License.Core.Common.LicenseHelper.ForceExit = true;//是否需要强制退出
                License.Core.Common.LicenseHelper.LoadRegister();
#endif
            }
            catch (Exception ex)
            {
                log.Error("加载注册类异常！", ex);
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        public void LoadData()
        {

            try
            {
                //读取配置文件中的配置
                ClientConfig.LoadConfig();

                //初始化
                new Thread(() =>
                {
                    GetInfo();//加载科室、诊室、医生信息
                    NotifyUpdate();//订阅当前医生的病人更新消息
                }).Start();

                //加载病人列表
                new Thread(() =>
                {
                    GetPatientList();
                }).Start();
            }
            catch (Exception ex)
            {
                log.Error("初始化数据异常！", ex);
            }
        }

        /// <summary>
        /// 加载科室、诊室、医生信息
        /// </summary>
        private void GetInfo()
        {
            try
            {
                string dept = ClientConfig.Dept;
                int room = ClientConfig.Room;
                string doctor = ClientConfig.Doctor;

                using (SQLContext db = new SQLContext())
                {
                    DeptInfo deptInfo = db.DeptInfos.FirstOrDefault(o => o.DeptCode == dept);
                    if (deptInfo != null)
                    {
                        this.tsslDept.Text = deptInfo.DeptName;
                    }

                    RoomInfo roomInfo = db.RoomInfos.FirstOrDefault(o => o.RoomCode == room);
                    if (roomInfo != null)
                    {
                        this.tsslRoom.Text = roomInfo.RoomName;
                    }

                    DoctorInfo doctorInfo = db.DoctorInfos.FirstOrDefault(o => o.DoctorCode == doctor);
                    if (doctorInfo != null)
                    {
                        this.tsslDoctor.Text = doctorInfo.DoctorName;
                    }

                }
            }
            catch (Exception ex)
            {
                log.Error("加载科室、诊室、医生信息异常！", ex);
                MessageBox.Show("加载科室、诊室、医生信息异常！原因：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载病人列表
        /// </summary>
        public void GetPatientList()
        {
            try
            {
                //清空当前就诊病人信息
                currentPatient = null;

                string dept = ClientConfig.Dept;
                int room = ClientConfig.Room;
                string doctor = ClientConfig.Doctor;

                //获取病人列表
                DateTime nowDate = DateTime.Now.Date;
                using (SQLContext db = new SQLContext())
                {
                    patientList = db.PatientInfos.Where(o => o.VisitDate == nowDate && o.VisitDept == dept && o.VisitRoom == room && o.VisitDoctor == doctor).OrderBy(o => o.QueueNo).ToList();
                }

                this.lvPatientList.Items.Clear();
                if (patientList != null && patientList.Count > 0)
                {
                    //添加数据
                    int index = 0;
                    foreach (PatientInfo patientInfo in patientList)
                    {
                        bool isRepeated = patientInfo.IsRepeated;
                        string itemText = string.Format("{0}{1}", patientInfo.NumberPrefix, Convert.ToString(patientInfo.Number)); 
                        string numberString = string.Format("{0}{1}", isRepeated ? "复" : "", Convert.ToString(patientInfo.QueueNo));

                        ListViewItem item = new ListViewItem();
                        item.Text = itemText;// 显示号
                        item.Name = Convert.ToString(patientInfo.Id);
                        item.Tag = Convert.ToString(patientInfo.Number);
                        item.ToolTipText = Convert.ToString(patientInfo.Number);
                        item.SubItems.Add(numberString);// 排队号

                        // 复诊红色文字
                        if (isRepeated)
                        {
                            item.ForeColor = Color.Red;
                            item.SubItems.Add(patientInfo.Name + "[复]");
                        }
                        else
                        {
                            item.SubItems.Add(patientInfo.Name);
                        }

                        item.SubItems.Add(patientInfo.Sex);
                        item.SubItems.Add(patientInfo.Age + " 岁");
                        item.SubItems.Add(patientInfo.Remark);
                        item.SubItems.Add(patientInfo.Status);
                        item.SubItems.Add(patientInfo.RegistrationNumber);

                        //根据状态添加背景颜色
                        if (patientInfo.Status == PatientStatus.Visiting)
                        {
                            item.BackColor = Color.YellowGreen;
                        }

                        if (patientInfo.Status == PatientStatus.ReQueuing)
                        {
                            item.BackColor = Color.Yellow;
                        }

                        if (patientInfo.Status == PatientStatus.Completed)
                        {
                            item.ForeColor = Color.Black;
                        }

                        this.lvPatientList.Items.Add(item);

                        //选中并滚动到指定行
                        if (patientInfo.Status == PatientStatus.Visiting)
                        {
                            this.lvPatientList.Items[index].Selected = true;//选中行
                            this.lvPatientList.EnsureVisible(index);//滚动到指定的行位置
                        }

                        index++;
                    }

                    //获取当前病人（就诊中）
                    currentPatient = patientList.FirstOrDefault(o => o.Status == PatientStatus.Visiting);

                    ShowCurrentPatientInfo(currentPatient);//刷新病人信息 
                }
            }
            catch (Exception ex)
            {
                log.Error("加载病人列表异常！", ex);
                MessageBox.Show("加载病人列表异常！原因：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新病人信息（暂时使用重新获取方法）
        /// </summary>
        private void UpdatePatientList()
        {
            try
            {
                // 如果已经更新完成并且间隔时间小于等于0
                //右下角通知提醒
                if (ClientConfig.Notify)
                {
                    try
                    {
                        new Thread(() =>
                        {
                            //提示框
                            ToastForm slice = new ToastForm(5000, "有新病人信息更新！");
                            slice.Height = 50;
                            slice.Show();
                        }).Start();
                    }
                    catch (Exception exce_toast)
                    {

                    }
                }

                //处理消息
                GetPatientList();

                log.Info("消息处理成功！");

            }
            catch (Exception exce)
            {
                log.Error("刷新病人信息（暂时使用重新获取方法）异常！", exce);
            }
        }

        /// <summary>
        /// 更新间隔秒数(10s内的更新请求只处理一次，防止重复处理导致界面无响应)
        /// </summary>
        int intervalSeconds = -1;
        /// <summary>
        /// 订阅当前医生的病人更新消息
        /// </summary>
        private void NotifyUpdate()
        {
            string channel = String.Format("Update_{0}_{1}_{2}", ClientConfig.Dept, ClientConfig.Room, ClientConfig.Doctor);

            try
            {
                redisHelper.Subscribe(channel, (redisChannel, redisValue) =>
                {
                    log.Info("频道 [ " + redisChannel + " ] 接收到消息内容：" + redisValue);

                    intervalSeconds = 10;

                    // 处理消息
                    // UpdatePatientList(redisChannel, redisValue);
                    // UpdatePatientList();
                });

                log.Info("订阅频道 [ " + channel + " ] 的消息成功！");

            }
            catch (Exception ex)
            {
                log.Error("订阅频道 [ " + channel + " ] 的消息异常！", ex);
                MessageBox.Show("订阅频道 [ " + channel + " ] 的消息异常！原因：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool CheckSetting()
        {
            bool isSuccess = false;
            if (!String.IsNullOrEmpty(ClientConfig.Dept) && ClientConfig.Room != 0 && !String.IsNullOrEmpty(ClientConfig.Doctor))
            {
                isSuccess = true;
            }
            else
            {
                this.tsslSetting_Click(null, null);
            }
            return isSuccess;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            CheckSetting();

            if (patientList != null)
            {
                PatientInfo patientInfo = null;

                if (currentPatient != null)
                {
                    //将之前病人就诊状态设置为：已完成
                    using (SQLContext db = new SQLContext())
                    {
                        PatientInfo tempPatientInfo = db.PatientInfos.FirstOrDefault(o => o.Id == currentPatient.Id);
                        if (tempPatientInfo != null)
                        {
                            tempPatientInfo.Status = PatientStatus.Completed;
                            db.SaveChanges();
                        }
                    }

                    //修改列表中的状态
                    bool isRepeated = currentPatient.IsRepeated;

                    string itemText = string.Format("{0}{1}", patientInfo.NumberPrefix, Convert.ToString(patientInfo.Number));
                    string numberString = string.Format("{0}{1}", isRepeated ? "复" : "", Convert.ToString(patientInfo.QueueNo));

                    ListViewItem currentItem = this.lvPatientList.FindItemWithText(itemText);
                    if (currentItem != null)
                    {
                        currentItem.SubItems[6].Text = PatientStatus.Completed;
                    }

                    //查询当前号之后的患者
                    //patientInfo = patientList.FirstOrDefault(o => o.Status == PatientStatus.Waiting && o.Id != currentPatient.Id && o.Number >= currentPatient.Number);// 如果有重号或者之前号有重新排队的人则无法叫到
                    patientInfo = patientList.Where(o => o.Status == PatientStatus.Waiting && o.Id != currentPatient.Id).OrderBy(o => o.QueueNo).ToList().Take(1).FirstOrDefault();

                    //如果没有之后的患者，则重新循环查询之前的患者
                    if (patientInfo == null)
                    {
                        patientInfo = patientList.OrderBy(o => o.QueueNo).FirstOrDefault(o => o.Status == PatientStatus.Waiting);
                    }
                }
                else
                {
                    patientInfo = patientList.FirstOrDefault(o => o.Status == PatientStatus.Waiting);
                }

                if (patientInfo != null)
                {
                    currentPatient = patientInfo;

                    //将当前病人就诊状态设置为：就诊中
                    using (SQLContext db = new SQLContext())
                    {
                        PatientInfo tempPatientInfo = db.PatientInfos.FirstOrDefault(o => o.Id == currentPatient.Id);
                        if (tempPatientInfo != null)
                        {
                            tempPatientInfo.Status = PatientStatus.Visiting;
                            db.SaveChanges();
                        }
                    }

                    ShowCurrentPatientInfo(currentPatient);//刷新病人信息

                    CallPatient(currentPatient); //呼叫病人

                    GetPatientList();//刷新病人列表
                }
                else
                {
                    try
                    {
                        string opt = SystemMessageCommand.Completed;

                        string dept = ClientConfig.Dept;
                        int room = ClientConfig.Room;
                        string doctor = ClientConfig.Doctor;

                        string channel = String.Format("System_{0}", dept);

                        // 科室|诊室|医生|消息
                        string command = string.Format("{0}|{1}|{2}|{3}", dept, room, doctor, opt);
                        long publishResult = redisHelper.Publish<string>(channel, command);

                        log.Info("发送系统消息成功！返回：" + publishResult);
                    }
                    catch (Exception ex)
                    {
                        log.Error("发送系统消息异常！", ex);
                    }

                    MessageBox.Show("没有等待就诊的病人了！\r\n 开始自动刷新...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    //如果还没有患者，刷新列表一次后提示
                    GetPatientList();
                }
            }
            else
            {
                MessageBox.Show("当前就诊病人列表为空，请等分诊台录入后操作！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ShowCurrentPatientInfo(PatientInfo patientInfo)
        {
            if (patientInfo != null)
            {
                string itemText = string.Format("{0}{1}", patientInfo.NumberPrefix, Convert.ToString(patientInfo.Number));

                //显示当前病人信息
                this.txtNumber.Text = Convert.ToString(patientInfo.Number);
                this.txtNumberShow.Text = itemText;
                this.txtName.Text = patientInfo.Name;
                this.txtSex.Text = patientInfo.Sex;
                this.txtAge.Text = patientInfo.Age + " 岁";
                this.txtRemark.Text = patientInfo.Remark;

                //当前就诊中病人颜色设置
                if (currentPatient != null)
                {
                    bool isRepeated = patientInfo.IsRepeated;
                    string numberString = string.Format("{0}{1}", isRepeated ? "复" : "", Convert.ToString(patientInfo.QueueNo));

                    ListViewItem currentItem = this.lvPatientList.FindItemWithText(itemText);
                    if (currentItem != null)
                    {
                        currentItem.BackColor = Color.GreenYellow;
                        currentItem.SubItems[6].Text = PatientStatus.Visiting;

                        //将其他病人背景色设置
                        int index = 0;
                        foreach (ListViewItem item in this.lvPatientList.Items)
                        {
                            //选中并滚动到指定行
                            if (item.Text == currentItem.Text)
                            {
                                this.lvPatientList.Items[index].Selected = true;//选中行
                                this.lvPatientList.EnsureVisible(index);//滚动到指定的行位置
                            }

                            //根据状态添加背景颜色
                            if (item.SubItems[6].Text == PatientStatus.Visiting)
                            {
                                item.BackColor = Color.YellowGreen;
                            }

                            if (item.SubItems[6].Text == PatientStatus.ReQueuing)
                            {
                                item.BackColor = Color.Yellow;
                            }

                            if (patientInfo.Status == PatientStatus.Completed)
                            {
                                item.ForeColor = Color.Black;
                            }

                            index++;
                        }
                    }
                }
            }
            else
            {
                //显示当前病人信息
                this.txtNumber.Text = "";
                this.txtNumberShow.Text = "";
                this.txtName.Text = "";
                this.txtSex.Text = "";
                this.txtAge.Text = "";
                this.txtRemark.Text = "";
            }
        }

        private void btnRecall_Click(object sender, EventArgs e)
        {
            CheckSetting();

            if (currentPatient != null)
            {
                //DialogResult result = MessageBox.Show("确认要重新呼叫病人 [ " + currentPatient.Number + " - " + currentPatient.Name + " ] 吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                //if (result == DialogResult.OK)
                //{
                CallPatient(currentPatient); //呼叫病人
                                             //}
            }
            else
            {
                MessageBox.Show("当前还没有就诊病人，请先按顺序呼叫！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 呼叫病人
        /// </summary>
        /// <param name="patientInfo"></param>
        private void CallPatient(PatientInfo patientInfo)
        {
            try
            {
                if (patientInfo != null)
                {
                    string dept = ClientConfig.Dept;
                    int room = ClientConfig.Room;
                    string doctor = ClientConfig.Doctor;

                    if (!String.IsNullOrEmpty(dept) && room != 0 && !String.IsNullOrEmpty(doctor))
                    {
                        string channel = "Call_" + dept;
                        long publishResult = redisHelper.Publish<PatientInfo>(channel, patientInfo);

                        log.Info("呼叫成功！返回：" + publishResult);
                    }
                    else
                    {
                        log.Error("呼叫失败！原因：未正确配置科室、诊室、医生信息！");
                        MessageBox.Show("呼叫失败！原因：未正确配置科室、诊室、医生信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    log.Error("呼叫失败！原因：传入病人信息为空！");
                    MessageBox.Show("呼叫失败！原因：传入病人信息为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                log.Error("呼叫病人异常！", ex);
                MessageBox.Show("呼叫病人异常！原因：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnReWaiting_Click(object sender, EventArgs e)
        {
            CheckSetting();

            if (currentPatient != null)
            {
                DialogResult result = MessageBox.Show("确认要将病人 [ " + currentPatient.Number + " - " + currentPatient.Name + " ] 标记为重排队吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result == DialogResult.OK)
                {
                    //修改列表中的状态
                    bool isRepeated = currentPatient.IsRepeated;
               
                    string itemText = string.Format("{0}{1}", currentPatient.NumberPrefix, Convert.ToString(currentPatient.Number));
                    string numberString = string.Format("{0}{1}", isRepeated ? "复" : "", Convert.ToString(currentPatient.QueueNo));

                    ListViewItem currentItem = this.lvPatientList.FindItemWithText(itemText);
                    if (currentItem != null)
                    {
                        currentItem.BackColor = Color.Yellow;
                        currentItem.SubItems[6].Text = PatientStatus.ReQueuing;
                    }

                    //将当前病人就诊状态设置为：重排队
                    using (SQLContext db = new SQLContext())
                    {
                        PatientInfo tempPatientInfo = db.PatientInfos.FirstOrDefault(o => o.Id == currentPatient.Id);
                        if (tempPatientInfo != null)
                        {
                            tempPatientInfo.Status = PatientStatus.ReQueuing;
                            db.SaveChanges();
                        }
                    }

                    //当前病人设置为空
                    currentPatient = null;

                    GetPatientList();
                }
            }
            else
            {
                MessageBox.Show("当前还没有就诊病人，请先按顺序呼叫！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void lvPatientList_MouseClick(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Right && this.lvPatientList.SelectedItems.Count == 1)
            //{
            //    this.contextMenuStrip.Show(MousePosition);
            //}

            this.tsmiReCall.Enabled = false;
            if (this.lvPatientList.SelectedItems != null && this.lvPatientList.SelectedItems.Count == 1)
            {
                ListViewItem currentItem = this.lvPatientList.SelectedItems[0];
                if (currentItem != null && currentItem.SubItems[6].Text == PatientStatus.ReQueuing)
                {
                    this.tsmiReCall.Enabled = true;
                }
            }
        }

        private void llRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.tsmiRefresh_Click(null, null);
        }

        private void tsmiRefresh_Click(object sender, EventArgs e)
        {
            GetPatientList();
        }

        private void tsmiReCall_Click(object sender, EventArgs e)
        {
            CheckSetting();

            try
            {
                ListViewItem currentItem = null;
                PatientInfo patientInfo = null;
                if (this.lvPatientList.SelectedItems != null && this.lvPatientList.SelectedItems.Count == 1)
                {
                    currentItem = this.lvPatientList.SelectedItems[0];
                    int currentItemIndex = currentItem.Index;
                    if (currentItem != null)
                    {
                        long id = 0;
                        string itemText = currentItem.Text;// string.Format("{0}{1}", currentPatient.NumberPrefix, Convert.ToString(currentPatient.Number));
                        string itemName = currentItem.Name;// Id
                        string itemTag = Convert.ToString(currentItem.Tag);// Number
                        if (!String.IsNullOrEmpty(itemTag) && long.TryParse(itemName, out id))
                        {
                            using (SQLContext db = new SQLContext())
                            {
                                // patientInfo = db.PatientInfos.FirstOrDefault(o => o.VisitDept == ClientConfig.Dept && o.VisitRoom == ClientConfig.Room && o.VisitDoctor == ClientConfig.Doctor && o.Number == number);
                                patientInfo = db.PatientInfos.FirstOrDefault(o => o.Id == id);
                                if (patientInfo != null)
                                {
                                    if (currentPatient != null)
                                    {
                                        //将之前病人就诊状态设置为：已完成
                                        PatientInfo tempPatientInfo = db.PatientInfos.FirstOrDefault(o => o.Id == currentPatient.Id);
                                        if (tempPatientInfo != null)
                                        {
                                            tempPatientInfo.Status = PatientStatus.Completed;
                                            db.SaveChanges();
                                        }

                                        //修改列表中的状态
                                        bool isRepeated = currentPatient.IsRepeated;

                                        string numberString = string.Format("{0}{1}", isRepeated ? "复" : "", Convert.ToString(currentPatient.QueueNo));

                                        ListViewItem tempCurrentItem = this.lvPatientList.FindItemWithText(itemText);
                                        if (tempCurrentItem != null)
                                        {
                                            tempCurrentItem.SubItems[6].Text = PatientStatus.Completed;
                                        }
                                    }

                                    //将选中病人设置为就诊中
                                    patientInfo.Status = PatientStatus.Visiting;
                                    db.SaveChanges();

                                    //设置为当前就诊病人
                                    currentPatient = patientInfo;
                                    ShowCurrentPatientInfo(currentPatient);

                                    CallPatient(currentPatient); //呼叫病人

                                    GetPatientList();//刷新病人列表
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                log.Error("重新呼叫重排队病人异常！", ex);
                MessageBox.Show("重新呼叫重排队病人异常！原因：" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            CheckSetting();

            string opt = "";
            string status = this.btnStop.Text;
            if (status == "暂 停")
            {
                DialogResult result = MessageBox.Show("确认要临时暂停就诊吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result == DialogResult.OK)
                {
                    this.btnStop.Text = "开 始";
                    this.btnStop.Image = Properties.Resources.start;

                    this.btnNext.Enabled = false;
                    this.btnRecall.Enabled = false;

                    //暂停
                    opt = SystemMessageCommand.Stop;
                }
            }
            else if (status == "开 始")
            {
                this.btnStop.Text = "暂 停";
                this.btnStop.Image = Properties.Resources.stop;

                this.btnNext.Enabled = true;
                this.btnRecall.Enabled = true;

                //暂停
                opt = SystemMessageCommand.Start;
            }

            try
            {
                string dept = ClientConfig.Dept;
                int room = ClientConfig.Room;
                string doctor = ClientConfig.Doctor;

                string channel = String.Format("System_{0}", dept);

                // 科室|诊室|医生|消息
                string command = string.Format("{0}|{1}|{2}|{3}", dept, room, doctor, opt);
                long publishResult = redisHelper.Publish<string>(channel, command);

                log.Info("发送系统消息成功！返回：" + publishResult);
            }
            catch (Exception ex)
            {
                log.Error("发送系统消息异常！", ex);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsslSetting_Click(object sender, EventArgs e)
        {
            SettingForm form = new SettingForm();
            DialogResult result = form.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // 重新加载数据
                LoadData();
            }

        }

        private void timerShowTime_Tick(object sender, EventArgs e)
        {
            this.tsslDateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            if (intervalSeconds > 0)
            {
                // 更新间隔时间
                intervalSeconds--;
            }
            else if (intervalSeconds == 0)
            {
                // 更新列表
                UpdatePatientList();
                // 更新完成后标记
                intervalSeconds = -1;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("您确认要退出吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();//强制所有消息中止，退出所有的窗体，但是若有托管线程（非主线程），也无法干净地退出
            Application.ExitThread();//强制中止调用线程上的所有消息，同样面临其它线程无法正确退出的问题
                                     //System.Environment.Exit(0);//这是最彻底的退出方式，不管什么线程都被强制退出，把程序结束的很干净
        }

        private void tsslRegister_Click(object sender, EventArgs e)
        {
            try
            {
#if DEBUG
                // License.Core.Common.LicenseHelper.LoadRegister();
#else
                License.Core.Common.LicenseHelper.LoadRegister();
#endif
            }
            catch (Exception ex)
            {
                log.Error("打开注册界面异常！", ex);
            }
        }
    }
}
